//
//  ST_SomeOneDailyViewController.swift
//  btvideo
//
//  Created by mac on 2020/7/23.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import MJRefresh

class ST_SomeOneDailyViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
         
        
        if let t = self.dailyModel{
            title_nav_btn.setTitleForAllStates("#"+t.name)
        }
        
        setupRightBtn()
        
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight + 44, left: 0, bottom: 0, right: 0))
        }
        
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        request_data()
        
    }
    
    
    fileprivate func setupRightBtn(){
        
        right_nav_btn.setTitleForAllStates("发布日常")
        let enableImg = UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1))
        right_nav_btn.setBackgroundImage(enableImg, for: UIControl.State.normal)
        right_nav_btn.cornerRadius = 30/2.0
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.semibold)
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.height.equalTo(30)
            make.width.equalTo(78)
        }
        
        right_nav_btn.isHidden = false
        right_nav_btn.alpha = 0
    }
    
    
    override func right_click() {
        
        
        let vc = ST_EditDailyMomentController()
        
        vc.model = dailyModel
        
        self.navigationController?.pushViewController(vc)
    }
    
//    MARK: - Properties
    
    var dailyModel:ST_DailBaseModel?
    
    fileprivate var first = true
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 10 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.register(cellWithClass: ST_DailyMomentCell.self)
        control.register(headerFooterViewClassWith: DailyMomentSectionOfCenterHeader.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = .white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.tableHeaderView = self.headerView
        
        control.emptyDataSetSource = self
        control.emptyDataSetDelegate = self
        
        return control
    }()

    
    fileprivate lazy var headerView:ST_SomeOneDailyHeader = {
        
        let control = ST_SomeOneDailyHeader.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 124))
        
        control.model = self.dailyModel
        
        return control
    }()
    
    
//    MARK: - Data
    fileprivate var currentPage = 0
    
    fileprivate var data_array = [DailyMomentOfHallModel]()
    
    /**
     1:最新,2:推荐(默认)
     */
    fileprivate var dataType = 2
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        var param = ["page":currentPage,
                     "daily_type":3,
                     "show_state":self.dataType,
                     "size":20] as [String : Any]
        
        if let m = self.dailyModel{
            param.updateValue(m.id, forKey: "daily_id")
        }
        
        JVrequest(PH.recommendDailyApi,parameters: param, success: { (json) in
            
            print("看看 数据呢：",json)
            
            let data = json["data"]
            
            let list = data["list"].arrayValue.map { (itemJson) -> DailyMomentOfHallModel in
                return DailyMomentOfHallModel.init(fromJson: itemJson)
            }
            
            if self.currentPage == 1{
                self.data_array = list
            }else{
                self.data_array += list
            }
            
            self.tableView.reloadData()
            
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
            self.tableView.footer_refresh(count: list.count) {[weak self] in
                
                self?.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
            
            
        }) { (code, err) in
            print("看看 数据呢-error：",err)
            self.toast(text: err)
        }
        
    }
    
}


extension ST_SomeOneDailyViewController:UITableViewDelegate,UITableViewDataSource{
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = tableView.dequeueReusableHeaderFooterView(withClass: DailyMomentSectionOfCenterHeader.self)
        
        
        view.selectClosure = {[weak self] index in
            
            self?.dataType = index
            
            self?.currentPage = 0
            
            self?.request_data()
            
            self?.tableView.scrollToTop()
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 64 - 15 - 10
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_DailyMomentCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        cell.reload_cell_closure = {[weak self] in
            
            if #available(iOS 13.0, *) {
                self?.tableView.reloadData()
            } else {
                self?.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.fade)
            }
        }
        
        cell.comment_click_closure = {[weak self] iCell in
            
            guard let model = iCell.model else{ return }
            
            let vc = ST_DaliyMomentDetailController()
            
            vc.dailyId = model.id.string
            
            vc.userId = model.accid
            
            vc.openInputCommentBar = true
            
            self?.navigationController?.pushViewController(vc)
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return data_array[indexPath.row].cellHeight
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = data_array[indexPath.row]
        
        let vc = ST_DaliyMomentDetailController()
        
        vc.dailyId = model.id.string
        
        vc.userId = model.accid
        
        self.navigationController?.pushViewController(vc)
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let y = scrollView.contentOffset.y
        
        let offSet = 123 - y
        
        if offSet < 0{
            
            right_nav_btn.alpha = 1
            
        }else if offSet >= own_navigation_bar_show_coefficient{
            
            right_nav_btn.alpha = 0
        }else{
            right_nav_btn.alpha = 1-offSet/own_navigation_bar_show_coefficient
        }
        
    }
    
}




extension ST_SomeOneDailyViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
        
        if first{
            self.first = false
            return false
        }else{
            return true
        }
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        let attrString = NSMutableAttributedString(string: "快来发第一条日常呀")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return ST_ImageUtils.imageName("首页_img_gift_empty")
    }
}
